package com.keqiang.filepicker.utils

import android.text.TextUtils
import android.webkit.MimeTypeMap
import java.util.*

/**
 * MIME辅助类，根据文件扩展名获取MIME类型、根据MIME获取文件扩展名、更加MIME类型判断资源类型（图片、视频、音频、二进制文件等）
 */
object MimeUtils {
    // 增加系统不支持的扩展
    private val mimeTypeToExtensionMap: MutableMap<String, String> = HashMap()
    private val extensionToMimeTypeMap: MutableMap<String, String> = HashMap()
    const val MIME_TYPE_JSON = "application/json"

    /**
     * 增加MIME类型
     *
     * @param mimeType  mime类型
     * @param extension mime类型对应文件的扩展名
     */
    private fun add(mimeType: String, extension: String) {
        // If we have an existing x -> y mapping, we do not want to
        // override it with another mapping x -> y2.
        // If a mime type maps to several extensions
        // the first extension added is considered the most popular
        // so we do not want to overwrite it later.
        if (!mimeTypeToExtensionMap.containsKey(mimeType)) {
            mimeTypeToExtensionMap[mimeType] = extension
        }

        if (!extensionToMimeTypeMap.containsKey(extension)) {
            extensionToMimeTypeMap[extension] = mimeType
        }
    }

    /**
     * 获取uri中文件的扩展名,如sdcard/0/a.txt、http://www.xxx.com/a.txt、a.txt等,返回"txt"
     *
     * @return 如果无匹配项，或无法识别的后缀名，则返回null。比如text.x,不会返回x
     */
    fun getFileExtensionFromUri(url: String): String? {
        var urlTemp = url
        var extension: String? = null
        if (!TextUtils.isEmpty(urlTemp)) {
            if (urlTemp.startsWith("http://") || urlTemp.startsWith("https://")) {
                val fragment = urlTemp.lastIndexOf('#')
                if (fragment > 0) {
                    urlTemp = urlTemp.substring(0, fragment)
                }
                val query = urlTemp.lastIndexOf('?')
                if (query > 0) {
                    urlTemp = urlTemp.substring(0, query)
                }
            }
            if (urlTemp.isNotEmpty()) {
                val dotPos = urlTemp.lastIndexOf('.')
                if (0 <= dotPos) {
                    urlTemp = urlTemp.substring(dotPos + 1)
                    if (hasExtension(urlTemp)) {
                        extension = urlTemp
                    }
                }
            }
        }

        return if (extension == null || extension.isEmpty()) {
            null
        } else extension.lowercase(Locale.getDefault())
    }

    /**
     * 获取url中文件的MIME,如sdcard/0/a.txt、http://www.xxx.com/a.txt、a.txt等,返回"text/plain"
     *
     * @return 如果无匹配项，或无法识别的后缀名，则返回null。比如text.x,无法识别.x扩展，返回null
     */
    fun getFileMimeFromUrl(url: String): String? {
        return getMimeTypeFromExtension(getFileExtensionFromUri(url))
    }

    /**
     * 根据MIME类型获取文件扩展名，如"image/jpeg",返回"jpeg"
     *
     * @return 如果无匹配项，则返回null
     */
    fun getExtensionFromMimeType(mimeType: String): String? {
        if (TextUtils.isEmpty(mimeType)) {
            return null
        }
        val mime = mimeType.lowercase(Locale.getDefault())
        var extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mime)
        if (extension == null) {
            extension = mimeTypeToExtensionMap[mime]
        }
        return extension
    }

    /**
     * 根据文件扩展名获取MIME类型，如"a.jpeg",返回"image/jpeg"
     *
     * @return 如果无匹配项，则返回null
     */
    fun getMimeTypeFromExtension(extension: String?): String? {
        if (TextUtils.isEmpty(extension)) {
            return null
        }
        val lowerCase = extension!!.lowercase(Locale.getDefault())
        var mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(lowerCase)
        if (mime == null) {
            mime = extensionToMimeTypeMap[lowerCase]
        }
        return mime
    }

    /**
     * 根据扩展名判断是否存在匹配的MIME类型
     */
    fun hasExtension(extension: String): Boolean {
        if (TextUtils.isEmpty(extension)) {
            return false
        }
        val lowerCase = extension.lowercase(Locale.getDefault())
        var hasExtension = MimeTypeMap.getSingleton().hasExtension(lowerCase)
        if (!hasExtension) {
            hasExtension = extensionToMimeTypeMap.containsKey(lowerCase)
        }
        return hasExtension
    }

    /**
     * 根据MIME类型判断是否存在匹配的扩展名
     */
    fun hasMimeType(mimeType: String): Boolean {
        if (TextUtils.isEmpty(mimeType)) {
            return false
        }
        val mime = mimeType.lowercase(Locale.getDefault())
        var hasMimeType = MimeTypeMap.getSingleton().hasMimeType(mime)
        if (!hasMimeType) {
            hasMimeType = mimeTypeToExtensionMap.containsKey(mime)
        }
        return hasMimeType
    }

    init {
        add(MIME_TYPE_JSON, "json")
    }
}